package DAO.DAOImple;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import DAO.AlbumDAO;

import model.Album;
import model.Page;
import util.DBTool;

public class AlbumImple implements AlbumDAO {
	
	/*
	 * @添加相册
	 * (non-Javadoc)
	 * @see DAO.PhotoDAO#addAlbum()
	 */
	public int addAlbum(Album album) {
		
		String sql = "INSERT INTO T_Album (albumName, createTime, description, creator) VALUES (?, ?, ?, ?)";
		
		int result = 0;
		PreparedStatement pstmt = null;
		DBTool dbt = DBTool.getDBTool();
		pstmt = dbt.getPstmt(sql);
		
		try {
			
			pstmt.setString(1, album.getAlbumName());
			pstmt.setString(2, (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
			pstmt.setString(3, album.getDescription());
			pstmt.setInt(4, album.getUser().getId());
			
			int temp = pstmt.executeUpdate();
			if(temp != 0) {
				result = 1;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbt.close(pstmt);
			dbt.closeConn();
		}
		return result;
	}
	
	/*
	 * @得到相册列表
	 * (non-Javadoc)
	 * @see DAO.PhotoDAO#getAlbumList(int, model.Page)
	 */
	public List<Album> getAlbumList(Page page) {
		
		String sql = "SELECT a.*, u.* FROM T_Album AS a, T_User AS u WHERE a.creator = u.id";
		
		Album album;
		List<Album> albumList = new ArrayList<Album>();
		
		PreparedStatement pstmt = null;
		ResultSet rst = null;
		DBTool dbt = DBTool.getDBTool();
		pstmt = dbt.getPstmt(sql);
		
		try{
			rst = pstmt.executeQuery();
			while(rst.next()) {
				album = new Album();
				album.setId(rst.getInt("a.id"));
				album.setAlbumName(rst.getString("a.albumName"));
			//	album.getUser().setName(rst.getString("u.name"));
			//	album.setCreatTime(rst.getDate("a.creatTime"));
				album.setDescription(rst.getString("a.description"));
				
				System.out.println();
				
				albumList.add(album);
			}
		} catch(SQLException e) {
			e.printStackTrace();
		} finally {
			dbt.close(rst);
			dbt.close(pstmt);
			dbt.closeConn();
		}
		
		return albumList;
	}
	
	/*
	 * @删除相册
	 * (non-Javadoc)
	 * @see DAO.PhotoDAO#deleteAlbum(int)
	 */
	public void deleteAlbum(int albumId) {
		
		String sql = "DELETE FROM T_Album WHERE id = ?";
		
		PreparedStatement pstmt = null;
		DBTool dbt = DBTool.getDBTool();
		pstmt = dbt.getPstmt(sql);
		
		System.out.println(albumId);
		
		try {
			pstmt.setInt(1, albumId);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbt.close(pstmt);
			dbt.closeConn();
		}
		
	}
	
}
